var app = getApp();
var appData = app.globalData;
Page({
  data: {
    canGetCode: true,
    phoneNumber: "",
    wxcode:'',
    btnonoff:true
  },
  onLoad:function() {
     let page=getCurrentPages(),arg='';
     page=page[page.length-2];
     if(page){
       for(var key in page.options){
         arg+='&'+key+'='+page.options[key]
       }
       arg=arg?arg.substring(1):'';
       const path='/'+page.route+'?'+arg;
       wx.getStorageSync('path')||wx.setStorageSync('path',path);
     }
  },
  onShow:function(){
    this.phoneLogin()
  },
  phoneLogin:function(){
    const self=this;
    wx.login({
      success: function success(res) {
        if (res.code) {
          self.data.wxcode=res.code;
          self.data.btnonoff=true;
        }
      }
    })
  },
  getPhoneNumber: function (data) {
    console.log(data);
    const self=this;
    console.log(self.data.wxcode)
    if(!self.data.btnonoff){return false;}
    self.data.btnonoff=true;
    self.wxphone(data,this.data.wxcode)
  },
  wxphone:function(data,code){
    const self=this;
    appData.Tool.info({code:code, iv: data.detail.iv, encryptedData: data.detail.encryptedData }).then(function (res) {
      wx.hideLoading();
      console.log(res);
      if (res.code == 0){
        res.data.token && wx.setStorageSync('token', res.data.token);
        app.loginBack()
      }else{
        wx.hideLoading();
        self.phoneLogin()
        wx.showToast({
          title: "授权失败请重新一键授权",
          icon: 'none',
          duration: 2000
        })
      }

    }).catch(function (error) {
      wx.hideLoading();
      self.phoneLogin()
      wx.showToast({
        title: error.message||'网络错误请稍后再试',
        icon: 'none',
        duration:2000
      })
    });
  },
  login:function(){
    wx.navigateTo({
      url:'/pages/phone/phone'
    })
  }
})
